﻿#pragma execution_character_set("utf-8")
#include "selfinfo.h"
#include "ui_selfinfo.h"

SelfInfo::SelfInfo(const QString &email,QVariantMap &map,QNetworkReply* reply,QWidget *parent):
    BaseInfo(map["msgId"].toString(),map["createTime"].toLongLong(),parent),
    ui(new Ui::SelfInfo),
    reply(reply)
{//msgId,type,content,createTime
    ui->setupUi(this);
    updateHeadImg(email);//设置头像
    QString type=map["type"].toString();
    if(type=="text"){//处理文字
        MessageStatus status=MessageStatus::LOADING;
        if(map.contains("isSend")){
            if(map["isSend"].toInt()!=1)
                status=MessageStatus::FAILURE;
            else
                status=MessageStatus::SUCCESS;
        }
        setText(map["content"].toString(),status);
        textRespond();
    }
    else if(type=="png"){//处理图片
        QString filePath=QString("./accountData/%1/Res/imageRes/%2").arg(email).arg(msgId+"."+type);
        MessageStatus status=MessageStatus::LOADING;
        if(map.contains("isSend")){
            if(map["isSend"].toInt()!=3)
                status=MessageStatus::FAILURE;
            else
                status=MessageStatus::SUCCESS;
        }
        setImage(filePath,status);
        textRespond();
    }
    else{//处理文件
        QString filePath=QString("./accountData/%1/Res/fileRes/%2").arg(email).arg(map["content"].toString()+"."+type);
        MessageStatus status=MessageStatus::LOADING;//设置初始状态
        if(map.contains("isSend")){
            int isSend=map["isSend"].toInt();
            if(isSend==0||isSend==2)//先上传文件+2，才触发发送信息+1，完成状态3，未完成状态0或2,1状态表示从服务器获取消息，但没有下载文件
                status=MessageStatus::FAILURE;
            else
                status=MessageStatus::SUCCESS;
        }
        setFile(filePath,status);
        fileResopnd();
    }
}

void SelfInfo::updateHeadImg(const QString &email){
    if(QFile::exists(QString("./accountData/%1/headImg/head.png").arg(email)))
    {
        ui->headImg_BT->setStyleSheet(QString("\
            QPushButton{\
                border:1px solid black;\
                border-radius:20px;\
                border-image: url('./accountData/%1/headImg/head.png') 0 0 0 0 stretch stretch;\
            }\
        ").arg(email));
    }
}

SelfInfo::~SelfInfo()
{
    delete ui;
}

void SelfInfo::setText(const QString &text,const MessageStatus &status){
    textEdit=new TextMessage(text,this);
    insertTextEdit(status);
    QFontMetrics fm(textEdit->font());
    textEdit->setMaximumWidth(fm.horizontalAdvance(text)+10);
}

void SelfInfo::setImage(const QString &filePath,const MessageStatus &status){
    if (filePath.isEmpty()) {//判断文件路径是否为空串
        setText("[图片不存在]",MessageStatus::SUCCESS);
        return;
    }
    {//判断文件是否存在
        QFileInfo fileInfo(filePath);
        if (!fileInfo.exists() || fileInfo.size() <= 0) {
            setText("[图片]",MessageStatus::SUCCESS);
            return;
        }
    }
    QSize targetSize=scaleImage(filePath);
    if(targetSize.isNull()){
        setText("[图片无法解析]",MessageStatus::SUCCESS);
        return ;
    }
    // 插入图片并设置其大小
    QTextImageFormat format;
    format.setName(filePath); // 设置图片的源路径（可选）
    format.setWidth(targetSize.width()); // 设置图片的宽度
    format.setHeight(targetSize.height()); // 设置图片的高度

    if(textEdit==nullptr){
        textEdit=new FileMessage(this);
        insertTextEdit(status);
        ((FileMessage*)textEdit)->setImage(format);
    }
}

void SelfInfo::setFile(const QString &filePath,const MessageStatus &status){
    if(fileInfo==nullptr){
        fileInfo=new FileInfo(filePath,this);
        connect(fileInfo,&FileInfo::downLoadFile,[this](){
            emit downLoadFile(this->msgId);
        });
        QHBoxLayout* content=(QHBoxLayout*)(ui->content_WT->layout());
        if(block==nullptr){
            block=new SpaceBlock(status,this);
            block->insertRight();
            content->insertWidget(0,block);
        }
        content->addWidget(fileInfo);
        QWidget* parentWidget=ui->content_WT->parentWidget();
        parentWidget->setFixedHeight(100);
        this->setFixedHeight(100+40);
    }
}

void SelfInfo::insertTextEdit(const MessageStatus &status){
    if(textEdit!=nullptr){
        QHBoxLayout* content=(QHBoxLayout*)(ui->content_WT->layout());
        if(block==nullptr){
            block=new SpaceBlock(status,this);
            block->insertRight();
            content->insertWidget(0,block,4);
        }
        content->addWidget(textEdit,6);
    }
}

void SelfInfo::insertTimeInfo(const QString &time){
    if(timeInfo==nullptr){
        timeInfo=new TimeInfo(time,this);
        ui->verticalLayout->insertWidget(0,timeInfo);
        if(textEdit!=nullptr){
            if(qobject_cast<FileMessage*>(textEdit)){
                this->setFixedHeight(height()+24);
            }
            else{
                TextMessage* baseMessage=qobject_cast<TextMessage*>(textEdit);
                if(baseMessage!=nullptr){
                    baseMessage->setIncreaseHight(24);
                }
            }
        }
        else
        {
            this->setFixedHeight(100+40+24);
        }
    }
}

void SelfInfo::textRespond(){
    if(reply!=nullptr){
        connect(reply,&QNetworkReply::finished,[this](){
            this->block->sendFinish();
            delete this->reply;
            this->reply=nullptr;
        });
        connect(reply,&QNetworkReply::errorOccurred,[this](QNetworkReply::NetworkError code){
            if(code!=QNetworkReply::NoError)
                this->block->sendFail();
        });
    }
}

void SelfInfo::fileResopnd(){
    if(reply!=nullptr){
        connect(reply,&QNetworkReply::uploadProgress,[this](qint64 bytesSent, qint64 bytesTotal){
            fileInfo->setFileStatus(ceil((float)bytesSent/(float)bytesTotal*100));
        });
        connect(reply,&QNetworkReply::finished,[this](){
            this->block->sendFinish();
            fileInfo->updateFileStatus();
            delete this->reply;
            this->reply=nullptr;
        });
        connect(reply,&QNetworkReply::errorOccurred,[this](QNetworkReply::NetworkError code){
            if(code!=QNetworkReply::NoError)
                this->block->sendFail();
        });
    }
}

